import { useChatStore } from '@/components/Chat/chatStore'
import { TitleIconBg } from '@/components/bs-comp/cardComponent'
// import ChatComponent from '@/components/bs-comp/chatComponent'
import { CHAT_URL } from '@/components/Chat/constants'
import ChatComponent from '@/components/Chat/index'
// import { NewApplicationIcon } from '@/components/bs-icons/newApplication'
import { useToast } from '@/components/bs-ui/toast/use-toast'
import { useAssistantStore } from '@/store/assistantStore'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { TabsContext } from '../../../contexts/tabsContext'
import { postBuildInit } from '../../../controllers/API'
import { getFlowApi } from '../../../controllers/API/flow'
import { FlowType, NodeType } from '../../../types/flow'
import { validateNode } from '../../../utils'

export default function ChatPanne({ customWsHost = '', data, conversation = '', useName = '' }) {
  const { id, chatId, type, conversation_id, disabled, tips, model_name, guideQuestion, user_name } = data
  // const guideQuestion = []
  const { t } = useTranslation()

  const [flow, setFlow] = useState<any>(null)
  const flowRef = useRef(null)
  const [assistant, setAssistant] = useState<any>(null)
  const { assistantState, chatloadAssistantState, loadAssistantState, destroy } = useAssistantStore()
  // console.log('data :>> ', flow);
  const build = useBuild()
  const { updateGuideMessage } = useChatStore()
  const [loading, setloading] = useState(true)

  useEffect(() => {
    return destroy
  }, [])

  const init = async () => {
    try {
      if (type === 'flow') {
        setAssistant(null)
        const _flow = await getFlowApi(id)
        await build(_flow, chatId)
        flowRef.current = _flow
        setFlow(_flow)
        if (_flow.guide_word) updateGuideMessage(_flow.guide_word, true)
      } else {
        flowRef.current = null
        setFlow(null)
        // 定义默认值
        const obj = {
          desc: '3333333333333333333333333333',
          system_prompt: '',
          prompt: '111',
          category_code: '4',
          temperature: 0.3,
          status: 1,
          user_id: 1,
          is_delete: 0,
          is_shadow: 1,
          support_search: true,
          reply_style: 1,
          enterprise_id: '100100',
          tool_ids: [],
          flow_ids: ['91cdaa08-bd37-4f7d-9731-bbde99dd7411'],
          knowledge_ids: [],
          update_time: '2025-01-07T17:11:53',
          flow_list: [
            {
              name: '乘法口诀表',
              user_id: 1,
              description: '能够输出学前教育的九九数学乘法口诀表：例如1*1=1',
              data: null,
              logo: 'https://viu-lpsdk-cdn.yuntiancloud.com/agent_platform/icons/91a9aaf878a2417db6742ad84897d4ef.png',
              status: 1,
              update_time: '2025-01-08T14:14:16',
              create_time: '2025-01-06T11:51:12',
              guide_word: null,
              id: '91cdaa08-bd37-4f7d-9731-bbde99dd7411',
              user_name: null,
              version_id: null
            }
          ],
          knowledge_list: [],
          tool_list: [],
          ...data
        }
        // setAssistant(obj)
        const _assistant = await chatloadAssistantState(obj)
        setAssistant(_assistant)
      }
    } catch (error) {
      console.error('An error occurred:', error)
    } finally {
      setloading(false)
    }
  }
  useEffect(() => {
    setloading(true)
    if (!id) {
      flowRef.current = null
      setFlow(null)
      setAssistant(null)
      setloading(false)
      return
    }
    init()
  }, [data])

  // sendmsg user name
  // const sendUserName = useMemo(() => {
  //   if (!flow) return ''
  //   const node = flow.data.nodes.find(el => el.data.type === 'AutoGenUser')
  //   return node?.data.node.template.name.value || ''
  // }, [flow])

  if (!(flow || assistant)) {
    return (
      <div className="chat-box bs-chat-bg flex h-full flex-1 flex-col items-center justify-center overflow-hidden">
        <div className="mt-[-80px]">
          <img className="h-[182px] w-[200px]" src="/application-start-logo.png" alt="" />
          <div className="mt-[20px] w-auto whitespace-normal text-center text-3xl font-light leading-[64px] text-[#111111] dark:text-[#D4D4D4]">
            选择一个
            <b className="font-semibold text-[#111111] dark:text-[#D4D4D4]">对话</b>
            <br />
            {/* {t('chat.start')} */}
            {/* <b className="font-semibold text-[#111111] dark:text-[#D4D4D4]">{t('chat.wenqingruijian')}</b> */}
          </div>
        </div>
        {/* {!customWsHost && (
          <div
            className="relative z-50 mx-auto mt-[120px] flex h-[38px] w-[162px] cursor-pointer justify-around rounded-lg bg-[#0055e3] text-[13px] leading-[38px] text-[white] hover:bg-[#0165e6]"
            onClick={() => {
              document.getElementById('newchat')?.click()
            }}
          >
            <span className="my-auto ml-[4px] block">
              <NewApplicationIcon />
            </span>
            <span className="mr-[28px]">{t('chat.newChat')}</span>
          </div>
        )} */}
      </div>
    )
  }

  return (
    <div className="bs-chat-bg min-h-0 min-w-0 flex-1">
      {/* 技能会话 */}
      {flow && (
        <div className={`chat-box relative h-full w-full px-6 ${type === 'flow' ? 'block' : 'hidden'}`}>
          {/* {flow && <ChatPanne chatId={chatId} flow={flow} />} */}
          <div className="absolute top-2 z-10 flex items-center gap-2 bg-[rgba(255,255,255,0.8)] px-2 py-1 dark:bg-[#1B1B1B]">
            <TitleIconBg className="" id={flow.id}></TitleIconBg>
            <span className="text-sm">{flow.name}</span>
          </div>
          <ChatComponent
            clear
            questions={guideQuestion}
            chatUrl={CHAT_URL}
            assistantId={id}
            prompt={assistantState.prompt}
            useName={useName}
            conversation={conversation}
            // form={flowSate.isForm}
            // guideWord={flow.guide_word}
            // wsUrl={wsUrl}
            // onBeforSend={getWsParamData}
            // loadMore={() => loadMoreHistoryMsg(flow.id)}
            // inputForm={flowSate.isForm ? <ChatReportForm flow={flow} onStart={sendReport} /> : null}
          />
        </div>
      )}
      {/* 助手会话 */}
      {/* 加载中... */}
      {loading && (
        <div className="left-270 absolute top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      {assistant && (
        <div className={`chat-box relative h-full w-full px-6 ${type !== 'flow' ? 'block' : 'hidden'}`}>
          {/* {flow && <ChatPanne chatId={chatId} flow={flow} />} */}
          {/* <div className="absolute top-2 z-10 flex items-center gap-2 bg-[rgba(255,255,255,0.8)] px-2 py-1 dark:bg-[#1B1B1B]">
            <TitleIconBg className="" id={assistant.id}>
              <AssistantIcon />
            </TitleIconBg>
            <span className="text-sm">{assistant.name}</span>
          </div> */}
          <ChatComponent
            clear
            questions={assistant.guide_question || []}
            chatUrl={CHAT_URL}
            assistantId={id}
            conversationId={conversation_id}
            prompt={assistantState.prompt}
            useName={useName}
            conversation={conversation}
            disabled={disabled}
            tips={tips}
            modelName={model_name}
            userName={user_name}
            // guideWord={assistant.guide_word}
            // useName={sendUserName}
            // guideWord={assistantState.guide_word}
            // wsUrl={wsUrl}
            // onBeforSend={getWsParamData}
            // loadMore={() => loadMoreHistoryMsg(assistant.id)}
            // inputForm={null}
          />
        </div>
      )}
    </div>
  )
}

/**
 * build flow
 * 校验每个节点，展示进度及结果；返回input_keys;end_of_stream断开链接
 * 主要校验节点并设置更新setTabsState的 formKeysData
 */

const useBuild = () => {
  const { toast } = useToast()
  const { setTabsState } = useContext(TabsContext)
  const { t } = useTranslation()

  // SSE 服务端推送
  async function streamNodeData(flow: FlowType, chatId: string) {
    // Step 1: Make a POST request to send the flow data and receive a unique session ID
    const { flowId } = await postBuildInit({ flow, chatId })
    // Step 2: Use the session ID to establish an SSE connection using EventSource
    const validationResults = []
    let finished = false
    let buildEnd = false
    const apiUrl = `/api/v1/build/stream/${flowId}?chat_id=${chatId}`
    const eventSource = new EventSource(apiUrl)

    eventSource.onmessage = event => {
      // If the event is parseable, return
      if (!event.data) {
        return
      }
      const parsedData = JSON.parse(event.data)
      // if the event is the end of the stream, close the connection
      if (parsedData.end_of_stream) {
        eventSource.close() // 结束关闭链接
        buildEnd = true
      } else if (parsedData.log) {
        // If the event is a log, log it
        // setSuccessData({ title: parsedData.log });
      } else if (parsedData.input_keys) {
        setTabsState(old => {
          return {
            ...old,
            [flowId]: {
              ...old[flowId],
              formKeysData: parsedData
            }
          }
        })
      } else {
        // setProgress(parsedData.progress);
        validationResults.push(parsedData.valid)
      }
    }

    eventSource.onerror = (error: any) => {
      console.error('EventSource failed:', error)
      eventSource.close()
      if (error.data) {
        const parsedData = JSON.parse(error.data)
        toast({
          title: parsedData.error,
          variant: 'error',
          description: ''
        })
      }
    }
    // Step 3: Wait for the stream to finish
    while (!finished) {
      await new Promise(resolve => setTimeout(resolve, 100))
      finished = buildEnd // validationResults.length === flow.data.nodes.length;
    }
    // Step 4: Return true if all nodes are valid, false otherwise
    return validationResults.every(result => result)
  }

  // 延时器
  async function enforceMinimumLoadingTime(startTime: number, minimumLoadingTime: number) {
    const elapsedTime = Date.now() - startTime
    const remainingTime = minimumLoadingTime - elapsedTime

    if (remainingTime > 0) {
      return new Promise(resolve => setTimeout(resolve, remainingTime))
    }
  }

  async function handleBuild(flow: FlowType, chatId: string) {
    try {
      const errors = flow.data.nodes.flatMap((n: NodeType) => validateNode(n, flow.data.edges))
      if (errors.length > 0) {
        return toast({
          title: t('chat.buildError'),
          variant: 'error',
          description: errors
        })
      }

      const minimumLoadingTime = 200 // in milliseconds
      const startTime = Date.now()

      await streamNodeData(flow, chatId)
      await enforceMinimumLoadingTime(startTime, minimumLoadingTime) // 至少等200ms, 再继续(强制最小load时间)
    } catch (error) {
      console.error('Error:', error)
    }
  }

  return handleBuild
}
